// src/stores/addressStore.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const useAddressStore = defineStore('address', () => {
  const addresses = ref([])
  const loading = ref(false)
  const error = ref(null)

  const fetchAddresses = async (userId) => {
    try {
      loading.value = true
      const response = await axios.get('/api/address/getAddress', { params: { userId } })
      if (response.data.status === 0) {
        addresses.value = response.data.data
      }
    } catch (err) {
      error.value = err.response?.data?.message || '获取地址失败'
    } finally {
      loading.value = false
    }
  }

  const addAddress = async (addressData) => {
    try {
      loading.value = true
      const response = await axios.post('/api/address/addAddress', addressData)
      if (response.data.status === 0) {
        await fetchAddresses(addressData.userId)
        return true
      }
    } catch (err) {
      error.value = err.response?.data?.message || '添加地址失败'
      return false
    } finally {
      loading.value = false
    }
  }

  const updateAddress = async (addressData) => {
    try {
      loading.value = true
      const response = await axios.post('/api/address/updateAddress', addressData)
      if (response.data.status === 0) {
        await fetchAddresses(addressData.userId)
        return true
      }
    } catch (err) {
      error.value = err.response?.data?.message || '更新地址失败'
      return false
    } finally {
      loading.value = false
    }
  }

  const deleteAddress = async (id) => {
    try {
      loading.value = true
      const response = await axios.post('/api/address/delAddress', { id })
      if (response.data.status === 0) {
        return true
      }
    } catch (err) {
      error.value = err.response?.data?.message || '删除地址失败'
      return false
    } finally {
      loading.value = false
    }
  }

  return {
    addresses,
    loading,
    error,
    fetchAddresses,
    addAddress,
    updateAddress,
    deleteAddress
  }
})